<?php
namespace app\wxapp\controller;


use app\BaseController;
use app\common\entity\Result;
use app\common\exception\AuthException;
use Firebase\JWT\JWT;
use think\App;


use think\facade\Cache;
use think\facade\Db;


class Base extends BaseController{

    //登录的用户 目前数据库中 用户和微信用户是分开的
    protected $user;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $request = request();
        $jwtKey = env('jwt.key');
        $token = $request->header("token");
        if(empty($token)){
            throw new AuthException("没有登录");
        }
        try{
            $payload = JWT::decode($token,$jwtKey, array('HS256'));
            if($payload){
                //检测登录时间 是否过期

                if($payload->exp < time()) {
                    throw new AuthException("没有登录");
                }

                $this->user = Cache::get(env("cachekey.wxapp")."#".$payload->id); //配置的名称应该统一，不然怕出错
                if(empty($this->user)){
                    $this->collectUserInfo($payload->id,$payload->exp);
                }
            }else{
                throw new AuthException("没有登录");
            }

        }catch (\Exception $e){
            throw $e;
        }

    }

    private function collectUserInfo($userId,$expireTime){
        $this->user =Db::table("wechat_user")->where(['id'=>$userId])->find();
        Cache::set(env("cachekey.wxapp")."#".$this->user['id'],$this->user,($expireTime - time())); //跟登录的时间有效期一样长
    }
}